package com.bamanker.cloudconsumer.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.bamanker.cloudapi.model.error.CommonErrorCode;
import com.bamanker.cloudapi.model.exception.BusinessException;
import com.bamanker.cloudconsumer.feign.BizClient;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.List;

/**
 * @author bamanker
 */
@Slf4j
@RestController
@RequiredArgsConstructor
public class ConsumerController {

    private final RestTemplate restTemplate;

    private final DiscoveryClient client;

    @Value("${spring.application.name}")
    private String appName;

    private final BizClient bizClient;

    @GetMapping("/test")
    @SentinelResource(value = "getUserInfo",
            blockHandler = "getUserInfoBlock",
            fallback = "getUserInfoFallback")
    public Object getUserInfo(@RequestParam(value = "key") String key) {
        return bizClient.getInfo(key);
    }

    public Object getUserInfoBlock(String key, BlockException e) {
        log.error("访问资源 getUserInfo 被限流，id={}", key);
        throw new BusinessException(CommonErrorCode.TOO_MANY_REQUEST, "访问资源 getUserInfo 被限流",e.getCause());
    }

    public String getUserInfoFallback(String key) {
        log.error("访问资源 getUserInfo 失败的fallback，id={}", key);
        return "访问资源 getUserInfo 失败，请稍后重试";
    }

    @GetMapping("/echo/app-name")
    public String echoAppName() {
        //使用 DiscoveryClient 和 RestTemolate 结合的方式来访问
        List<ServiceInstance> instances = client.getInstances("nacos-sys");
        ServiceInstance serviceInstance = instances.get(0);
        String url = String.format("http://%s:%s/echo/%s", serviceInstance.getHost(), serviceInstance.getPort(), appName);
        log.info("request url:" + url);
        String result = restTemplate.getForObject(url, String.class);
        log.info("result -> {}", result);
        return result;
    }

}
